<template>
	<view class="empty-container">
		<u-sticky offset-top="0">
			<view class="m-tabbar-container">
				<u-tabs :list="tabsTitle" @change="tabschange" :current="activeKey" lineColor="#4A76F7" :inactiveStyle="{color: '#8091A4', fontSize: '28rpx'}" :activeStyle="{ color: '#333333', fontWeight: '500'}"></u-tabs>
			</view>
		</u-sticky>
		
		<!-- 可开票记录 -->
		<block v-if="activeKey == 0">
			<view class="filtrate-group-btn">
				<scroll-view :scroll-x="true" style="width: 100%px;overflow:hidden;">
					<view class="btn-group-box">
						<view class="btns" v-for="(item,i) in btnGroup" :key="i" :class="activeIndex == i ? 'active' : ''" @click="handleBtnSwitch(item, i)">{{item.name}}</view>
					</view>
				</scroll-view>
			</view>
			
			<view class="list-container">
				<view class="title">
					<text class="text">当前发票</text>
					<text class="text-2">（56条）</text>
				</view>
				
				<view class="ul">
					<view class="li" v-for="(item, i) in invoiceRecordList" :key="i" @click="handleJumpDetail(item)">
						<view class="public-row">
							<view class="left-text">关联账单</view>
							<view class="right-text">{{item.bill_text}}</view>
						</view>
						<view class="public-row">
							<view class="left-text">发票金额</view>
							<view class="right-text">{{item.receipt_amount}}</view>
						</view>
						<view class="public-row">
							<view class="left-text">发票类型</view>
							<view class="right-text">{{getBillTYpe(item)}}</view>
						</view>
						<view class="public-row">
							<view class="left-text">申请时间</view>
							<view class="right-text">{{item.open_time}}</view>
						</view>
						<view class="status-name" :class="setClassNam(item)">{{setName(item)}}</view>
						<view v-if="item.status == 4" class="reson">{{item.cancel_remark}}</view>
					</view>
				</view>
			</view>
		</block>
		<!-- 可开票 -->
		<block v-else>	
			<view class="make-invoice">
				<view class="title">
					<text class="text">当前账单</text>
					<text class="text-2">（1条）</text>
				</view>
				<view class="box">
					<tm-checkbox-group @change="boxlistchange" v-model="checkboxlist" direction="customCol">
						<tm-checkbox class="my-checkgroup" :round="10" v-for="(item,i) in receiptInvoiceList" :key="i" :value="item.order_number" :_style="{'backgroundColor':'#FFFFFF', 'borderColor': '#E5E6EB'}">
						    <template v-slot:default="{checked}">
						        <view class="list">
									<view class="left-box">
										<view class="tit">{{item.bill_text}}</view>
										<view class="time">{{item.created_at}}</view>
									</view>
									<view class="right">
										<view class="tit">可开金额</view>
										<view class="money">{{item.receivable_amount}}</view>
									</view>
						        </view>
						    </template>
						</tm-checkbox>
					</tm-checkbox-group>
				</view>
				<view class="fixed-bottom-container">
					<view class="left-box">
						<tm-checkbox class="my-checkgroup" :_style="{'backgroundColor':'#FFFFFF', 'borderColor': '#E5E6EB'}" :indeterminate="banxuan" :fontSize="32" :round="10" v-model="allCheckbox" @change="allChange" :value="true" label="全选"></tm-checkbox>
						<view class="count-container">
							<text class="color-text">{{checkboxlist.length}}</text>
							<text>笔账单</text>
							<text style="margin-left: 20rpx;">共</text>	
							<text class="color-text">{{sum}}</text>
							<text>元</text>
						</view>	
					</view>
					<view class="right-box">
						<view class="next-btn" @click="handleNextBtn">下一步</view>
					</view>
				</view>
			</view>
			
		</block>
	</view>
</template>

<script setup lang="ts">
	import {ref, reactive, watch} from 'vue';
	import { onPageScroll, onLoad, onReachBottom } from '@dcloudio/uni-app';
	import tmTabs from '@/tmui/components/tm-tabs/tm-tabs.vue';
	import tmCheckbox from '@/tmui/components/tm-checkbox/tm-checkbox.vue';
	import tmCheckboxGroup from '@/tmui/components/tm-checkbox-group/tm-checkbox-group.vue';
	import { invoiceRecord, receiptIinvoiceList } from '@/api_request/invoiceList';
	import { useInfoStore } from '@/store/userInfo';
	import { storeToRefs } from 'pinia';
	const userStore = useInfoStore()
	const {userInfo} = storeToRefs(userStore)
	
	const tabsTitle = ref([
		{ 
			name: '开票记录', 
			badge: {
				value: 5,
			},
		},
		{ 
			name: '可开票',
			badge: {
				value: 5,
			}
		}
	])
	
	const btnGroup = ref([
		{name: '全部', status: 0},
		{name: '申请中', status: 1},
		{name: '已开票', status: 2},
		{name: '已红冲', status: 3},
		{name: '已退款', status: 4}
	])
	
	const activeIndex = ref<number>(0)
	const activeKey = ref<string | number>(0)
	const banxuan = ref(false)
	const allCheckbox = ref(false)
	const checkboxlist = ref([])
	const invoiceRecordList = ref([])
	const receiptInvoiceList = ref([])
	const isLoading = ref(false)
	const sum = ref<string | number>(0)
	const pageParams = reactive({
		page_num: 1,
		page_size: 10,
		community_id: userInfo.value.community_id, // 项目id
		merchant_id: userInfo.value.merchant_id, // 租户id
		status: 0, // 全部
	})
	onLoad( async () => {
		await handleClearData()
		await getInvoiceRecordList()
	})
	onReachBottom(() => {
		if(isLoading.value) return
		pageParams.page_num+=1
		getInvoiceRecordList()
	})
	watch(()=> checkboxlist.value, (newVal, oldVal) => {
		let count = 0
		if(newVal.length == 0) return sum.value = 0
		newVal.forEach((item:any) => {
			receiptInvoiceList.value.forEach((ele:any) => {
				if(item == ele.order_number) {
					count += Number(ele.receivable_amount)
				}
			})
		})
		sum.value = (count+'').includes('.') ? count : count + '.00'
	},{deep: true})
	const handleClearData =()=> {
		activeIndex.value = 0
		sum.value = 0
		activeKey.value = 0
		console.log('21112122', activeKey.value)
		banxuan.value = false
		allCheckbox.value = false
		checkboxlist.value = []
		invoiceRecordList.value = []
		receiptInvoiceList.value = []
		handleClearPageParams()
	}
	// 开票记录
	const getInvoiceRecordList = async (isFilter:boolean=false)=> {
		isLoading.value = true
		const {data, code, message} = await invoiceRecord(pageParams)
		isLoading.value = false
		if(code == 200) {
			console.log('=====12323=========', data);
			if(!isFilter) {
				invoiceRecordList.value = [...invoiceRecordList.value, ...data.list]
			}else {
				invoiceRecordList.value = data.list
			}
			
		}else {
			uni.$showMsg(message)
		}
	}
	// tba 切换
	const tabschange = async (item:any)=> {
		activeKey.value = item.index
		if(activeKey.value == 0) {
			await handleClearPageParams();
			await getInvoiceRecordList();
		}else {
			await getAeceiptIinvoiceList()
		}
	}
	// 开票记录 筛选
	const handleBtnSwitch = (row:any, i:number)=> {
		pageParams.page_num = 1;
		activeIndex.value = i;
		pageParams.status = row.status;
		getInvoiceRecordList(true);
	}
	//  清空筛选项
	const handleClearPageParams = ()=> {
		pageParams.page_num = 1;
		pageParams.page_size = 10;
		pageParams.status = 0;
	}
	
	const getAeceiptIinvoiceList = async ()=> {
		const params = {
			community_id: userInfo.value.community_id, // 项目id
			merchant_id: userInfo.value.merchant_id, // 租户id
		}
		const {data, code, message} = await receiptIinvoiceList(params)
		if(code == 200) {
			console.log('===================data', data);
			receiptInvoiceList.value = data
		}else {
			uni.$showMsg(message)
		}
	}
	
	const allChange = (e: boolean)=> {
		if (e == false) {
			checkboxlist.value = []
			banxuan.value = false
		} else if (e == true) {
			checkboxlist.value = receiptInvoiceList.value.map((item: any) => item.order_number)
			banxuan.value = false
		}
	}
	
	const boxlistchange = (e: Array<string>)=> {
		if (e.length == 0) {
			banxuan.value = false
			allCheckbox.value = false
		} else if (e.length == receiptInvoiceList.value.length) {
			banxuan.value = false
			allCheckbox.value = true
		} else {
			banxuan.value = true
			allCheckbox.value = true
		}
	}
	
	//  设置类名
	const setClassNam = (val:any)=> {
		// 1、待开票 2、已开票 3、已红冲 4、已退票
		const params = {
			'1': 'application',
			'2': 'open',
			'3': 'punch',
			'4': 'punch'
		}
		return params[val.status]
	}
	//  设置类名
	const setName = (val:any)=> {
		// 1、待开票 2、已开票 3、已红冲 4、已退票
		const params = {
			'1': '申请中',
			'2': '已开票',
			'3': '已红冲',
			'4': '已退票'
		}
		return params[val.status]
	}
	
	const getBillTYpe =(val:any) => {
		//1、增值税普通发票（电子）2、增值税普通发票（纸质）3、增值税专用发票（电子）4、增值税专用发票（纸质）
		const params = {
			'1': '增值税普通发票（电子）',
			'2': '增值税普通发票（纸质）',
			'3': '增值税专用发票（电子）',
			'4': '增值税专用发票（纸质）'
		}
		return params[val.receipt_type]
	}
	const handleJumpDetail = (item:any) => {
		uni.navigateTo({
			url: `/subpkg/empty_detail/index?id=${item.id}`
		})
	}
	
	// 下一步
	const handleNextBtn = ()=> {
		if(checkboxlist.value.length < 1) return uni.$showMsg('请选择勾选项')
		let billType:string = '多笔账单'; // 账单类型
		const arr:[] = [];
		receiptInvoiceList.value.forEach((ele:any) => {
			checkboxlist.value.forEach((item:any) => {
				if(ele.order_number == item) {
					arr.push(ele.bill_text)
				}
			})
		})
		billType = arr.every((item:string) => item == arr[0]) ? arr[0] : '多笔账单'
		uni.navigateTo({
			url: `/subpkg/apply_empty/index?sum=${sum.value}&billType=${billType}&orderId=${JSON.stringify(checkboxlist.value)}`
		})
	}
</script>

<style lang="scss" scoped>
	.empty-container {
		background: #F6F8FC;
		// min-height: 100%;
		padding-bottom: 80rpx;
		box-sizing: border-box;
		.m-tabbar-container {
			background-color: #FFFFFF;
		}
		.filtrate-group-btn {
			padding: 20rpx;
			box-sizing: border-box;
			
			.btn-group-box {
				white-space: nowrap;
				
				.btns {
					display: inline-flex;
					padding: 16rpx 32rpx;
					box-sizing: border-box;
					color: #8091A4;
					font-size: 28rpx;
					margin-right: 20rpx;	
					border-radius: 30rpx;
					background-color: #FFFFFF;
				}
				
				.btns.active {
					background: rgba(74,118,247,0.2);
					color: #165DFF;
				}
			}
		}
		
		.list-container {
			margin-top: 20rpx;
			padding: 0 20rpx;
			box-sizing: border-box;
			
			.title {
				display: flex;
				align-items: center;
				
				.text {
					font-size: 32rpx;
					font-weight: 500;
					color: #333333;
				}
				
				.text-2 {
					font-size: 24rpx;
					color: #8091A4;
				}
			}
			
			.ul {
				margin-top: 24rpx;
				
				.li {
					background: #FFFFFF;
					border-radius: 10rpx;
					padding: 30rpx 40rpx 40rpx;
					box-sizing: border-box;
					position: relative;
					margin-bottom: 20rpx;
					
					.public-row {
						display: flex;
						align-items: center;
						margin-top: 34rpx;
						
						.left-text {
							font-size: 28rpx;
							color: #8091A4;
							margin-right: 110rpx;
						}
						
						.right-text {
							font-size: 28rpx;
							color: #333333;
						}
					}
					
					.public-row:first-child {
						margin-top: 0;
					}
					
					.status-name {
						background: #F2F3F5;
						border-radius: 0rpx 10rpx;
						padding: 14rpx 20rpx;
						font-size: 28rpx;
						color: #88929E;
						position: absolute;
						top: 0;
						right: 0;
					}
					.status-name.application {
						background: #E8F3FF;
						color: #165DFF;
					}
					.status-name.open {
						background: #E8FFEA;
						color: #00B42A;
					}
					
					.reson {
						padding: 16rpx 20rpx;
						box-sizing: border-box;
						background-color: #FFF4E8;
						border-radius: 30rpx;
						margin-top: 24rpx;
						font-size: 28rpx;
						color: #FF7D00;
					}
				}
				
				.li:last-child {
					margin-bottom: 0;
				}
			}
		}
		
		.make-invoice {
			padding: 40rpx 20rpx 20rpx 20rpx;
			box-sizing: border-box;
			
			.title {
				display: flex;
				align-items: center;
				
				.text {
					font-size: 32rpx;
					font-weight: 500;
					color: #333333;
				}
				
				.text-2 {
					font-size: 24rpx;
					color: #8091A4;
				}
			}
			
			.box {
				margin-top: 24rpx;
				
				.my-checkgroup {
					background-color: #FFFFFF;
					padding: 40rpx;
					box-sizing: border-box;
					margin-bottom: 20rpx;
					
					::v-deep .flex .flex-row-center-start {
						.flex-shrink {
							.flex-shrink.round-10 {
								border-color: #E5E6EB !important;
							}
						}
					}
					
					.list {
						display: flex;
						justify-content: space-between;
						width: 570rpx;
						
						.left-box {
							.tit {
								font-size: 28rpx;;
								color: #333333;
							}
							
							.time {
								margin-top: 24rpx;
								font-size: 24rpx;
								color: #8091A4;
							}
						}
						
						.right {
							.tit {
								font-size: 24rpx;
								color: #165DFF;
							}
							
							.money {
								margin-top: 24rpx;
								font-size: 28rpx;
								color: #333333;
							}
						}
					}
				}
			}
			
			.fixed-bottom-container {
				position: fixed;
				bottom: 0;
				left: 0;
				width: 100%;
				padding: 16rpx 40rpx 24rpx;
				padding-bottom: constant(safe-area-inset-bottom);
				padding-bottom: env(safe-area-inset-bottom);
				box-sizing: border-box;
				width: 100%;
				background: #FFFFFF;
				
				display: flex;
				justify-content: space-between;
				.left-box {
					display: flex;
					flex-direction: column;
					
					.my-checkgroup {
						
						
						::v-deep .flex .flex-row-center-start {
							.flex-shrink {
								.flex-shrink.round-10 {
									border-color: #E5E6EB !important;
								}
							}
						}
					}
					
					.count-container {
						margin-top: 14rpx;
						display: flex;
						font-size: 28rpx;
						color: #8091A4;
						
						.color-text {
							color: #165DFF;
						}
						
						.margin-left {
							margin-right: 20rpx;
						}
					}
				}
				
				.right-box {
					.next-btn {
						width: 280rpx;
						height: 92rpx;
						background: #4A76F7;
						border-radius: 100rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 32rpx;
						color: #FFFFFF;
					}
				}
			}
		}
	}
</style>
